package com.lemon.utils;

import com.alibaba.fastjson.JSONObject;
import com.lemon.feign.BilibiliFeign;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BiliBiliHttpInterface {
    public static String searchUrl = "https://api.bilibili.com/x/space/wbi/arc/search";

    static public final String AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36";
    static public final String COOKIE = "i-wanna-go-back=-1; buvid_fp_plain=undefined; DedeUserID=162981410; DedeUserID__ckMd5=72575eb890793f39; CURRENT_BLACKGAP=0; blackside_state=0; rpdid=|(RlRkl|uJ~0J'uYY)~J~YRR; fingerprint=36843d81fd26cf011a8f8163cd8208b5; SESSDATA=6d20e063%2C1690793138%2Caec20%2A21; bili_jct=d812090bd42cdd6985a24c9fc52235f9; buvid4=4064EEC4-C080-27D2-CC5B-C7A9C0926EB667626-022021411-%2BZCMR%2B2k%2F7A1yLPRmWQHlw%3D%3D; LIVE_BUVID=AUTO8816762793753374; buvid3=17C4FCD2-EA50-BDCC-766A-E90232F27A3820097infoc; b_nut=1676518420; _uuid=AA1710AB9-F1010D-DE5C-C9E4-DBAF8E126D1B20144infoc; b_ut=5; nostalgia_conf=-1; CURRENT_PID=7f96a1f0-ceee-11ed-99aa-d1e74d5467ad; hit-new-style-dyn=1; hit-dyn-v2=1; header_theme_version=CLOSE; home_feed_column=5; bp_video_offset_162981410=785857927386759300; CURRENT_QUALITY=80; FEED_LIVE_VERSION=V_LIVE_2; CURRENT_FNVAL=4048; browser_resolution=1920-913; is-2022-channel=1; buvid_fp=219bd41defbf5ba32f2aabe55c25968e; PVID=4; sid=6vdj2pcf; bp_t_offset_162981410=792906973761765399; innersign=0; b_lsid=3AFC41101_18804A79179";

    @Autowired
    BilibiliFeign bilibiliFeign;


    public String search(String mid, int pn) {
        String q = "mid=" + mid +"&pn=" + pn;

        long wts = System.currentTimeMillis() / 1000;
        String reMap = getReMap(wts);

        String temp = q + "&wts=" + wts + reMap;
        String wrid= DigestUtils.md5Hex(temp);
        q = q + "&w_rid=" + wrid + "&wts=" + wts;
        return HttpConnect.doGet(searchUrl, q, AGENT, COOKIE);
    }


    public String getReMap(long wts){
        String nav1 = bilibiliFeign.nav();
        JSONObject nav = JSONObject.parseObject(nav1);

        // 提取img_key和sub_key
        String imgKey = nav.getJSONObject("data").getJSONObject("wbi_img").getString("img_url").replaceAll(".*/([^/]+)\\.png", "$1");
        String subKey = nav.getJSONObject("data").getJSONObject("wbi_img").getString("sub_url").replaceAll(".*/([^/]+)\\.png", "$1");
        // 拼接并打乱重排mixin_key
        String mixinKey =  imgKey + subKey;
        return StringMapUtils.getMixinKey(mixinKey);
    }
}
